// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require('axios');

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
    const collection = db.collection('logs')
    try {
        const res = await collection.where({
            title: db.RegExp({
                regexp: event.q, // 指定的字符串
                options: 'i' // 忽略大小写
            })
        }).limit(10).get()
        console.log('数据库查询结果', res)
        const dbList = res.data || [];

        const url = 'https://spapi.searchencrypt.com/api/search'; // 要代理的外部接口URL
        const headers = {
            "Referer": "https://www.searchencrypt.com/",
            "Referrer-Policy": "strict-origin-when-cross-origin",
            'Content-Type': 'application/json' // 设置请求头中的Content-Type
        };
        const param = {
            st: 'web',
            q: event.q,
            types: 'web'
        }; // 请求体中的数据
        const response = await axios.get(url, {
            params: param,
            headers
        }); // 发送POST请求
        const interfaceList = response.data.Results.map(item => {
            return {
                content: item.Content,
                link: item.ClickUrl,
                title: item.Title
            }
        }) || [];
        console.log('接口查询结果', interfaceList)
        return {
            code: 0,
            msg: '查询成功',
            // data: dbList
            data: dbList.concat(interfaceList)
        }
    } catch (error) {
        console.error(error)
        throw '查询错误';
    }
}